# -*-coding:utf-8-*-

import pyrestful.rest
from pyrestful import mediatypes
from pyrestful.rest import get, post, put, delete
from pymongo.collection import ReturnDocument
from utils.auth import authenticated
import time, json
from datetime import datetime, timedelta
from handlers.base import BaseHandler
from tornado.gen import coroutine


class RolesHandler(BaseHandler):
    def __init__(self, application, request, **kwargs):
        super(RolesHandler, self).__init__(application, request, **kwargs)

    def check_permissions(self, permissions):
        return True

    # @authenticated
    # @get(_path='/platform/api/roles', _produces=mediatypes.APPLICATION_JSON)
    # def get_role_list(self):
    #     result = self.roles_dao.get_role_list(self.user_id)
    #     self.response_success(result)

    @post(_path='/platform/api/roles')
    @authenticated
    @coroutine
    def create_role(self):
        data = json.loads(self.request.body)
        result = yield self.roles_dao.create_role(self.user_id, data)
        self.respond_success(result)

    @get(_path='/platform/api/roles/{rid}', _type=[str])
    @authenticated
    @coroutine
    def get_role(self, rid):
        result = yield self.roles_dao.get_role(self.user_id, rid)
        self.respond_success(result)

    @put(_path='/platform/api/roles/{rid}', _type=[str],
         _consumes=mediatypes.APPLICATION_JSON)
    @authenticated
    @coroutine
    def update_role(self, rid, request):
        result = yield self.roles_dao.update_role(self.user_id, rid, request)
        self.respond_success(result)

    # TODO: 判断若有下级角色存在，不允许删除
    @delete(_path='/platform/api/roles/{rid}', _types=[str])
    @authenticated
    @coroutine
    def delete_role(self, rid):
        result = yield self.roles_dao.delete_role(self.user_id, rid)
        self.respond_success(result)

    @get(_path='/platform/api/roles/{rid}/{aspect}', _types=[str, str])
    @authenticated
    @coroutine
    def get_role_aspect(self, rid, aspect):
        if 'subordinates' == aspect:
            result = yield self.roles_dao.get_role_subordinates(self.user_id, rid)
        elif 'siblings' == aspect:
            result = yield self.roles_dao.get_role_siblings(self.user_id, rid)
        else:
            raise Exception('invalid path: %s' % aspect)
        self.respond_success(result)
